﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class SocketConnectReceive : MonoBehaviour,SocketListener {

    #region socket相关
    #region 启动关闭socket连接
    public void StartSocket(bool force = false)
    {
        StartCoroutine(DoStartSocket(force));
    }

    IEnumerator DoStartSocket(bool force = true)
    {

        SocketConnectInfo connectInfo = SocketConnectInfo.Instance;
        connectInfo.roomId = string.Empty;//把房间号置为空后就不会进行游戏登入了

        SocketManager socketManager = SocketManager.Instance;
        yield return socketManager;
        socketManager.socketListener = this;

        UnityEngine.Debug.Log("CK : ------------------------------ PlatformGameDefine.playform.SocketLobbyUrl = " + "连接url");

        //socketManager.Connect(connectInfo, PlatformGameDefine.playform.SocketLobbyUrl, force); //socket 开始连接
    }
    public virtual void SocketReceiveMessage(byte[] message)
    {

    }
    public void EndSocket(bool disconnect = false)
    {//不会回调 SocketDisconnect
        if (SocketManager.Instance && SocketManager.Instance.socketListener == this)
        {
            SocketManager.Instance.socketListener = null;
            if (disconnect) SocketManager.Instance.Disconnect("Exit Scene " + name);//false
        }
    }
    #endregion 启动关闭socket连接

    #region 发送socket消息
    public static void SocketSendMessage(JSONObject json)
    {
        SocketManager.Instance.SendPackageWithJson(json);
    }
    #endregion 发送socket消息

    #region SocketListener回调方法
    public virtual void SocketReceiveMessage(string message)
    {
        UnityEngine.Debug.Log("CK : ------------------------------ message = " + message);

        // json处理
        JSONObject messageObj = new JSONObject(message);
        if (messageObj["type"] == null) return;
        string type = messageObj["type"].str;
        string tag = messageObj["tag"].str;

        
        
    }


    #region socket断开连接
    public virtual void SocketDisconnect(string disconnectInfo)
    {
    }

    public virtual void OnSocketDisconnect(string disconnectInfo)
    {
        SocketManager.Instance.socketListener = null;
        //PlatformGameDefine.playform.swithSocketLobbyHostUrl(); 更换连接url
        StartSocket(true);
    }
    #endregion socket断开连接
    #endregion SocketListener回调方法

    /* ------ Socket Process ------ */

    #region 大厅登入相关
    public virtual void Process_account_login_Failed(string errorInfo)
    {
        SocketDisconnect(errorInfo);//登入失败会自动断开,断开后会自动在OnSocketDisconnect 重连
    }

    
    #endregion 大厅登入相关

    #region 对socket请求和监听消息的结构处理
    /*
    /// <summary>
    /// 对 SocketReceiveMessage 监听的封装
    /// </summary>
    /// <param name="messageObj"></param>
    private void OnReceive(JSONObject messageObj)
    {
        if (!messageObj.IsAvailable() || !messageObj["result"].IsAvailable()) return;

        string path = messageObj["type"].str + "/" + messageObj["tag"].str;
        string result = messageObj["result"].str;

        if (m_SocketReSendMap.ContainsKey(path)) m_SocketReSendMap.Remove(path);//已经处理的消息,从这里移除

        if ("ok".Equals(result))
        {
            if (m_SocketRequestMap.ContainsKey(path) && m_SocketRequestMap[path] != null)
                m_SocketRequestMap[path](messageObj["body"]);

            if (m_SocketRequest_StrResult_Map.ContainsKey(path) && m_SocketRequest_StrResult_Map[path] != null)
                m_SocketRequest_StrResult_Map[path](messageObj["body"].ToString());
        }
        else
        {
            if (m_SocketRequestErrorMap.ContainsKey(path) && m_SocketRequestErrorMap[path] != null)
                m_SocketRequestErrorMap[path](result);
        }
    }

    /// <summary>
    /// 监听 SocketReceiveMessage 的消息
    /// </summary>
    /// <param name="path"></param>
    /// <param name="onReceiveAction">请求成功的回调,该值为空则不会添加该接受action</param>
    /// <param name="onErrorAction">请求出错的回调,该值为空则不会添加该接受action</param>
    public void Receive(string path, System.Action<JSONObject> onReceiveAction, System.Action<string> onErrorAction)
    {
        if (onReceiveAction != null) m_SocketRequestMap[path] = onReceiveAction;
        if (onErrorAction != null) m_SocketRequestErrorMap[path] = onErrorAction;
    }

    /// <summary>
    /// 监听 SocketReceiveMessage 的消息
    /// 主要考虑lua中使用
    /// </summary>
    /// <param name="path"></param>
    /// <param name="onReceiveAction">请求成功的回调,该值为空则不会添加该接受action</param>
    /// <param name="onErrorAction">请求出错的回调,该值为空则不会添加该接受action</param>
    public void Receive_lua(string path, System.Action<string> onReceiveAction, System.Action<string> onErrorAction)
    {
        if (onReceiveAction != null) m_SocketRequest_StrResult_Map[path] = onReceiveAction;
        if (onErrorAction != null) m_SocketRequestErrorMap[path] = onErrorAction;
    }

    /// <summary>
    /// 请求socket接口,处理 JSONObject 数据, onReceiveAction 直接处理body内容
    /// </summary>
    /// <param name="path"></param>
    /// <param name="body">如果body为空,那么该项填空字符串, 如果该项为null,那么只会进行Receive操作</param>
    /// <param name="onReceiveAction">请求成功的回调,该值为空则不会添加该接受action</param>
    /// <param name="onErrorAction">请求出错的回调,该值为空则不会添加该接受action</param>
    public void Request(string path, JSONObject body, System.Action<JSONObject> onReceiveAction, System.Action<string> onErrorAction)
    {
        if (body != null) ProtocolHelper.Send(path, body);
        Receive(path, onReceiveAction, onErrorAction);

        if (body != null && (onReceiveAction != null || onErrorAction != null)) m_SocketReSendMap[path] = body.ToString();
    }

    /// <summary>
    /// 请求socket接口,直接处理string格式数据, onReceiveAction 直接处理body内容
    /// 主要考虑lua中的使用string 比较方便
    /// </summary>
    /// <param name="path"></param>
    /// <param name="bodyJsonStr">如果body为空,那么该项填空字符串, 如果该项为null,那么只会进行Receive操作</param>
    /// <param name="onReceiveAction">请求成功的回调,该值为空则不会添加该接受action</param>
    /// <param name="onErrorAction">请求出错的回调,该值为空则不会添加该接受action</param>
    public void Request_lua(string path, string bodyJsonStr, System.Action<string> onReceiveAction, System.Action<string> onErrorAction)
    {
        if (bodyJsonStr != null) ProtocolHelper.Send(path, new JSONObject(bodyJsonStr));
        Receive_lua(path, onReceiveAction, onErrorAction);

        if (bodyJsonStr != null && (onReceiveAction != null || onErrorAction != null)) m_SocketReSendMap[path] = bodyJsonStr;
    }
        */
    #endregion 对socket请求和监听消息的结构处理
    #endregion socket相关
}
